export function checkAuth() {
    const token = sessionStorage.getItem('token');
    if (!token && !window.location.href.endsWith('login.html')) {
        window.location.href = 'login.html';
    }
}

export async function login(username, password) {
    const res = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
    });

    const data = await res.json();
    if (data.code === 200) {
        sessionStorage.setItem('token', data.data);
        window.location.href = '/index.html';
    } else {
        alert('登录失败，请检查用户名或密码');
    }
}

export function logout() {
    console.log('logout')
    sessionStorage.removeItem('token');
    window.location.href = '/login.html';
}

